#include "ads111x.h"

#define  false  ((uint8_t)0)
#define  true   ((uint8_t)1)
#ifdef ADS1110
void ADS111X_Init(void)
{
  uint8_t Buffer[] ={0x8C};
  BUZZER_Period(1);
  printf("ADS1110 initializing...");
  IIC2_Send_8_CLK();
  while(IIC2_Mem_Write(ADC_Address, Buffer[0],NULL, 0) == false );
  printf("\rADS1110 initialization is finished!!\r\n");
}



float read_ADS111X(void)
{
    int16_t result = 0;
    uint8_t *p =  (uint8_t *) &result;
    float _result =0; 
    uint8_t _address =  (ADC_Address<<1);
    IIC2_Start();
    IIC2_Send_Byte(_address | 0x01);
    *(p+1) = IIC2_Read_Byte(1); // high byte
    *p = IIC2_Read_Byte(1); // low byte
    IIC2_Read_Byte(0);
    IIC2_Stop();
   // result -= 231;
   // printf("\tresult = %d", result);
  //   _result = 56*2.048*result/32768;
    _result = 0.0035*result;
    _result = _result - 0.5f;
    return _result;
}

#else 
void ADS111X_Init(void)
{
  uint8_t Buffer[] ={0xC0,0xE3};
 // uint8_t Buffer[] ={0x90,0xE3};
  HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9,GPIO_PIN_RESET);  
  BUZZER_Period(1);
  HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9,GPIO_PIN_SET);
  BUZZER_Period(1);
  printf("ADS1115 initializing...");
  while(IIC2_Mem_Write(ADC_Address, 0x01, Buffer, 2) == false );
  printf("\rADS1115 initialization is finished!!\r\n");
}

float read_ADS111X(void)
{
  uint8_t Buffer[2] = {0};
  int16_t result = 0;
  float _result =0;
  uint8_t status = 0;
  while(1)
  {
    if(IIC2_Mem_Read(ADC_Address, 0, Buffer, 2) == true)
    {
      break;
    }
    else
    {
      IIC2_Send_8_CLK();
    }
  }
  
  if(status==HAL_OK)
  {
    result = Buffer[1] | (Buffer[0]<<8);
#ifdef ADC_DEBUG    
    printf("The battery current voltage is \033[40;33m%f\033[0m V\r\n",6.144*result/32768);
#endif 
    _result = 16*6.144*result/32768;
  } 
  return _result;
}

#endif

